//
//  UIApplication+VisibleViewController.m
//  suRead
//
//  Created by Kobe LI on 16/4/27.
//  Copyright © 2016年 bao. All rights reserved.
//

#import "UIApplication+VisibleViewController.h"
#import "AppDelegate.h"

@implementation UIApplication (VisibleViewController)

- (UIViewController *)visibleViewController
{
    UIViewController *rootViewController = [(AppDelegate *)self.delegate window].rootViewController;
    return [self visibleViewController:rootViewController];
}

- (UIViewController *)visibleViewController:(UIViewController *)rootViewController
{
    if ([rootViewController isKindOfClass:[UINavigationController class]])
    {
        UINavigationController *navigationController = (UINavigationController *)rootViewController;
        UIViewController *lastViewController = [[navigationController viewControllers] lastObject];
        
        return [self visibleViewController:lastViewController];
    }
    if ([rootViewController isKindOfClass:[UITabBarController class]])
    {
        UITabBarController *tabBarController = (UITabBarController *)rootViewController;
        UIViewController *selectedViewController = tabBarController.selectedViewController;
        
        return [self visibleViewController:selectedViewController];
    }
    
    if (rootViewController.presentedViewController != nil)
    {
        UIViewController *presentedViewController = (UIViewController *)rootViewController.presentedViewController;
        return [self visibleViewController:presentedViewController];
    }
    
    return rootViewController;
}

@end
